Conditions | 6 |
Paths | 1 |
Total Lines | 52 |
Lines | 52 |
Ratio | 100 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | View Code Duplication | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.arrayToObject = f()}})(function(){var define,module,exports;module={exports:(exports={})}; |
|
19 | module.exports = function(arr, mapBy) { |
||
20 | var obj = {}; |
||
21 | |||
22 | if (!Array.isArray(arr)) { |
||
23 | throw new TypeError('arr argument is not of type Array'); |
||
24 | } |
||
25 | |||
26 | if (mapBy !== undefined |
||
27 | && typeof mapBy !== 'string' |
||
28 | && !Array.isArray(mapBy) |
||
29 | && typeof mapBy !== 'function' |
||
30 | ) { |
||
31 | throw new TypeError( |
||
32 | 'mapBy argument is not of type {String|Array|Function}' |
||
33 | ); |
||
34 | } |
||
35 | |||
36 | var methods = { |
||
37 | string: function(val) { |
||
38 | this.undefined(val, val[mapBy]); |
||
39 | }, |
||
40 | object: function(val) { |
||
41 | var newKey = mapBy.map(function(propertyName){ |
||
42 | return val[propertyName]; |
||
43 | }).join('_'); |
||
44 | |||
45 | this.undefined(val, newKey); |
||
46 | }, |
||
47 | function: function(val, i, arr) { |
||
48 | this.undefined(val, mapBy(val, i, arr)); |
||
49 | }, |
||
50 | undefined: function(val, newKey) { |
||
51 | if (typeof newKey === 'string' |
||
52 | || typeof newKey === 'number' |
||
53 | ) { |
||
54 | obj[newKey] = val; |
||
55 | } |
||
56 | } |
||
57 | }; |
||
58 | |||
59 | /** |
||
60 | * run the designated method by mapBy type from the methods object |
||
61 | * it binds the methods object so we can use the undefined setter method |
||
62 | * for different mapBy types and don't have to maintain multiple but |
||
63 | * same conditions |
||
64 | */ |
||
65 | arr.forEach( |
||
66 | methods[(typeof mapBy)].bind(methods) |
||
67 | ); |
||
68 | |||
69 | return obj; |
||
70 | }; |
||
71 | |||
73 |